package com.qf.smsplatform.strategy.strategy.Impl;

import com.qf.smsplatform.common.constants.RabbitMQConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * projectName: smsplatform
 *
 * @author: MaTianWei
 * time: 2021/8/12 21:00
 * description:路由策略
 */
@Service(value = "router")
@Slf4j
public class RouterStrategyImpl implements Strategy {

    @Autowired
    private AmqpAdmin amqpAdmin;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("[策略模块-路由策略] =====开始执行=====");
        String queueName = null;
        try {
            //将submit再次作为消息发送到指定队列
            //1声明需要将当前消息发送到哪个队列中
            queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + submit.getGatewayID();
            //2创建队列,可以在RabbitMQ中创建
            amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
            //3发送消息到待发Topic
            rabbitTemplate.convertAndSend(queueName,submit);
        } catch (AmqpException e){
            PushErrorMessageUtil.sendLog(submit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            PushErrorMessageUtil.sendReport(submit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            log.error("[策略模块-路由策略] 发送消息到TOPIC失败 queueName = {}",queueName,e.getMessage());
            return false;
        }
        log.info("[策略模块-路由策略] =====执行成功=====");
        return true;
    }
}
